package com.dem.android.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.dem.android.db.DemsDBSchema.Tables;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "dems.android.db";
	private static final int DATABASE_VERSION = 7;

	DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		StringBuilder sql = new StringBuilder(1024);
		sql.append("CREATE TABLE ")
				.append(Tables.DEMS).append(" (")
				.append(DemsColumns._ID.getName()).append(" INTEGER PRIMARY KEY AUTOINCREMENT , ")
				.append(DemsColumns.THUMBNAIL.getName()).append(" TEXT,")
				.append(DemsColumns.URL_DETAIL.getName()).append(" TEXT,")
				.append(DemsColumns.TYPE.getName()).append(" TEXT,")
				.append(DemsColumns.PAGE.getName()).append(" TEXT,")
				.append("UNIQUE (").append(DemsColumns.THUMBNAIL.getName()).append(") ON CONFLICT REPLACE)");
		db.execSQL(sql.toString());
		sql.setLength(0);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(DatabaseHelper.class.getSimpleName(), "Upgrading database from v." + oldVersion + " to v." + newVersion);

		// drop all tables
		final String tables[] = { Tables.DEMS };
		for (final String table : tables)
			db.execSQL("DROP TABLE IF EXISTS " + table);

		onCreate(db);
	}

}